/**
 * Copyright (C) 2005 WUZEWEN. All rights reserved.
 * WZW PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.kingcore.pda.database.controller;

                 
import java.io.File;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.kingcore.framework.bean.DbBean;
import com.kingcore.framework.context.ApplicationContext;
import com.kingcore.pda.PdaContext;
import com.kingcore.pda.base.controller.PdaAction;
import com.kingcore.pda.core.bean.SmartCodeStyle;
import com.kingcore.pda.core.util.DbUtils;
import com.kingcore.pda.core.util.LangUtil;
import com.kingcore.pda.database.bean.DatabaseColumnBean;
import com.kingcore.pda.database.bean.DatabaseDictionary;
import com.kingcore.pda.database.bean.DatabaseTableBean;
import com.kingcore.pda.database.bean.impl.MySqlDatabaseDictionary;
import com.kingcore.pda.database.bean.impl.OracleDatabaseDictionary;
import com.kingcore.pda.database.bean.impl.SqlServer2005DatabaseDictionary;
import com.kingcore.pda.database.bean.impl.SqlServerDatabaseDictionary;
import com.kingcore.pda.project.bean.CompanyBean;
import com.kingcore.pda.project.bean.ModuleBean;
import com.kingcore.pda.project.bean.ProjectBean;
 

/**
 * <p>Description: oracle/sqlserver2000数据库表信息生成 *.woo.table 文件到目录(可配置)："E:/ProgramXP/test/" </p>
 * <p>Copyright: Copyright (c) 2005 WUZEWEN</p>
 * @author	WUZEWEN on 2005-7-27
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @see		Object#hashCode()
 * @see		HashMap
 * @since	JDK5
 */


public class TableFileAction extends PdaAction {

	Map<String,Object> data = new HashMap<String,Object>(); //data包含对象：companyBean.projectBean.moduleBean,...table

	ModuleBean moduleBean = new ModuleBean();
	
	
	protected synchronized void doCreateCodeFile(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		// var url = '/pda/createCodeFile.wsp?tblName=${param.tblName}';
		// url+='&columns=${columns}'
		// url+='&moduleName='+$("#moduleName").val()
		// url+='&jetfile='+file;

		this.createTableFile(mapping, request, response);

		String moduleName = null;
		String moduleLabel = null;

		data.put("module", moduleBean);
		moduleBean.setName(moduleName);
		moduleBean.setLabel(moduleLabel);
		moduleBean.setComment(moduleLabel);

		// this.saveError(request);
		request.setAttribute("data", data);

	}
	
    public ActionForward executeAction(ActionMapping mapping, ActionForm form, 
    									HttpServletRequest request, 
    									HttpServletResponse response)
								throws ServletException, Exception{
		
		String action = request.getParameter("action"); // wzw:action好于Action

		if (action == null || "".equals(action.trim())) { // 创建表文件的默认行为
			return this.createTableFile(mapping, form, request, response);

		} else { // 如果action不为空，反射调用对应方法
			System.out.println("开始调用Action方法：" + action);
			// JavaBean内部属性和ResultSet中一致时候
			Method setMethod = this.getClass().getMethod(action,
					ActionMapping.class, ActionForm.class,
					HttpServletRequest.class, HttpServletResponse.class);

			return (ActionForward) setMethod.invoke(this, 
					mapping, form,
					request, response);

		}
    	
	}
    
    
    public ActionForward modModuleProp(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		//获取prefix信息
		String projectCode=request.getParameter("projectCode");	//从客户端取编号 
		String tableEn=request.getParameter("tblName"); 
		String colEn=request.getParameter("colEn"); 
		String colComment=request.getParameter("colComment"); 
  
		//System.out.println( new String( colComment.getBytes("utf-8"),"gb2312") ); 
		//colComment = new String( colComment.getBytes("iso8859-1"), "gbk") ;  //utf-8
	
		CompanyBean comanpyBean = new CompanyBean();
		ProjectBean prjBean = PdaContext.getProjectMap().get(projectCode);
		String dbType=prjBean.getDbType();   //pro.getProperty( conf_prefix+"dbType");
		String poolName=prjBean.getPoolName();
		String dbName = prjBean.getDbName();
		System.out.println( "projectCode = " + projectCode );
		data.put("project", prjBean);
		data.put("company", comanpyBean); 


		//创建数据库连接
		String sql ="";
		Connection conn = null;
		try{
			//得到数据库连接 
//			conn = ApplicationContext.getInstance().getDataSourceManager().getConnection( poolName );
//			DbBean dbBean = new DbBean();
//			dbBean.setConnection(conn);
//
//			DatabaseDictionary dd = null;
//			String colScript = colComment;
//			if(dbType.equals("oracle")){
//				dd = new OracleDatabaseDictionary();
//				
//			}else if(dbType.equalsIgnoreCase("sqlServer")){
//				dd = new SqlServerDatabaseDictionary();
//				
//			}else if(dbType.equalsIgnoreCase("mySQL")){
//				dd = new MySqlDatabaseDictionary();
//				sql =  new StringBuffer().append(" select t.Column_Type as type_full,t.Column_Default,")
//						.append(" case t.IS_NULLABLE when 'YES' then 'null' else 'not null' end as NULLABLE")
//						.append(" ,INSTR(t.extra,'auto_increment') as isAutoIncrement")
//						.append(" from information_schema.COLUMNS t")
//						.append(" where t.table_name='"+tableEn+"'")
//						.append(" and t.Column_name='"+colEn+"'")
//						.append(" and t.TABLE_SCHEMA='"+dbName+"'").toString();
//				Map<String,Object> map = (Map<String, Object>) dbBean.queryForMap(sql);
//				System.out.println( map.get("isautoincrement") + sql );
//				//VARCHAR(32) NULL DEFAULT NULL COMMENT '系统名称2'
//				colScript  = map.get("type_full") +     //字段名称必须全部小写
//						" " + ("1".equals(map.get("isautoincrement")+"")?"Not Null":map.get("nullable"));
//				colScript += " " + (map.get("default")==null?("null".equals(map.get("nullable"))?"DEFAULT null":""):("DEFAULT "+map.get("default")) );
//				colScript += " " + ("1".equals(map.get("isautoincrement")+"")?"AUTO_INCREMENT":"");
//				colScript += " " + "COMMENT '"+colComment+"'" ;
//			} 
//			sql = dd.createUpdateCommentSql(dbName, tableEn,colEn, colScript );
//			dbBean.executeUpdate(sql);

			response.setContentType("text/plain; charset=gbk");
			response.getWriter().println("修改表模块信息成功！");
			
		}catch (Exception e){
			e.printStackTrace();
			response.setContentType("text/plain; charset=gbk");
			response.getWriter().println("修改表模块信息失败:"+e.getMessage());
		}finally{
			wzw.util.DbUtils.closeQuietly(conn);
		}
			 
		return null;
	}
    
    public ActionForward modColProperty(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		//获取prefix信息
		String projectCode=request.getParameter("projectCode");	//从客户端取编号 
		String tableEn=request.getParameter("tblName"); 
		String colEn=request.getParameter("colEn"); 
		String colComment=request.getParameter("colComment"); 
  
		//System.out.println( new String( colComment.getBytes("utf-8"),"gb2312") ); 
		colComment = new String( colComment.getBytes("iso8859-1"), "gbk") ;  //utf-8
	
		CompanyBean comanpyBean = new CompanyBean();
		ProjectBean prjBean = PdaContext.getProjectMap().get(projectCode);
		String dbType=prjBean.getDbType();   //pro.getProperty( conf_prefix+"dbType");
		String poolName=prjBean.getPoolName();
		String dbName = prjBean.getDbName();
		System.out.println( "projectCode = " + projectCode );
		data.put("project", prjBean);
		data.put("company", comanpyBean); 


		//创建数据库连接
		String sql ="";
		Connection conn = null;
		try{
			//得到数据库连接 
			conn = ApplicationContext.getInstance().getDataSourceManager().getConnection( poolName );
			DbBean dbBean = new DbBean();
			dbBean.setConnection(conn);

			DatabaseDictionary dd = null;
			String colScript = colComment;
			if(dbType.equals("oracle")){
				dd = new OracleDatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("sqlServer")){
				dd = new SqlServerDatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("sqlServer2005")){
				dd = new SqlServer2005DatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("mySQL")){
				dd = new MySqlDatabaseDictionary();
				sql =  new StringBuffer().append(" select t.Column_Type as type_full,t.Column_Default,")
						.append(" case t.IS_NULLABLE when 'YES' then 'null' else 'not null' end as NULLABLE")
						.append(" ,INSTR(t.extra,'auto_increment') as isAutoIncrement")
						.append(" from information_schema.COLUMNS t")
						.append(" where t.table_name='"+tableEn+"'")
						.append(" and t.Column_name='"+colEn+"'")
						.append(" and t.TABLE_SCHEMA='"+dbName+"'").toString();
				Map<String,Object> map = (Map<String, Object>) dbBean.queryForMap(sql);
				System.out.println( map.get("isautoincrement") + sql );
				//VARCHAR(32) NULL DEFAULT NULL COMMENT '系统名称2'
				colScript  = map.get("type_full") +     //字段名称必须全部小写
						" " + ("1".equals(map.get("isautoincrement")+"")?"Not Null":map.get("nullable"));
				colScript += " " + (map.get("default")==null?("null".equals(map.get("nullable"))?"DEFAULT null":""):("DEFAULT "+map.get("default")) );
				colScript += " " + ("1".equals(map.get("isautoincrement")+"")?"AUTO_INCREMENT":"");
				colScript += " " + "COMMENT '"+colComment+"'" ;
			} 
			sql = dd.createUpdateCommentSql(dbName, tableEn,colEn, colScript );
			dbBean.executeUpdate(sql);

			response.setContentType("text/plain; charset=gbk");
			response.getWriter().println("修改表模块属性信息成功！");
			
		}catch (Exception e){
			e.printStackTrace();
			response.setContentType("text/plain; charset=gbk");
			response.getWriter().println("修改表模块属性信息失败:"+e.getMessage());
		}finally{
			wzw.util.DbUtils.closeQuietly(conn);
		}
			 
		return null;
	}
    
    public ActionForward defineTableModule(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		//获取prefix信息
		String projectCode=request.getParameter("projectCode");	//从客户端取编号
		
		fetchModuleList( mapping, form, request, response );
		System.out.println("================ "+ moduleList.size() );
		request.setAttribute("moduleList", moduleList);
		String url = "/database/" + "defineTableModule.jsp";
		request.getRequestDispatcher( url ).forward(request,response);
		return null;
	}
    
    
	public ActionForward fetchTableModule(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		data = new HashMap<String,Object>();
		
		//获取prefix信息
		String projectCode=request.getParameter("projectCode");	//从客户端取编号
		
		fetchModuleList( mapping, form, request, response );
		System.out.println("================ "+ moduleList.size() );

		//获取request参数信息和配置文件值
		String is_tblname = request.getParameter("table0");
		if (is_tblname==null) {
			is_tblname = request.getParameter("tblName");
		}
		
		if (StringUtils.isNotBlank(is_tblname)) {
			this.createTableFile(mapping, request, response); ///form, 
		}

		request.setAttribute("data", data);
		request.setAttribute("moduleList", moduleList);
		String url = "/database/" + "defineTableModule.jsp";
		request.getRequestDispatcher( url ).forward(request,response);
		return null;
	}
    
	public ActionForward geneSystemMenuSql(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		System.out.println("开始执行：geneSystemMenuSql");
		//获取prefix信息
		String projectCode=request.getParameter("projectCode");	//从客户端取编号
		
		fetchModuleList( mapping, form, request, response );
		System.out.println("================ "+ moduleList.size() );
		request.setAttribute("moduleList", moduleList);
		String url = "/database/" + "generateSystemMenuSql.jsp";
		request.getRequestDispatcher( url ).forward(request,response);
		return null;
	}

	List<HashMap<String, String>> moduleList = new ArrayList<HashMap<String,String>>();
	public ActionForward fetchModuleList(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
  		
		//获取prefix信息
		String projectCode=request.getParameter("projectCode");	//从客户端取编号
		
		CompanyBean comanpyBean = new CompanyBean();
		ProjectBean prjBean = PdaContext.getProjectMap().get(projectCode);
		log.debug("projectCode = " + projectCode );
		data.put("project", prjBean);
		data.put("company", comanpyBean);
		comanpyBean.setCode(prjBean.getCompanyCode());
		comanpyBean.setName(prjBean.getCompanyName());
		
		//System.out.println ("aa"+conf_prefix);
		if(projectCode==null || projectCode.trim().equals("null") || projectCode.trim().equals("")){
			//System.out.println ("faddd");
			projectCode= "cannotFind";
		}else{
			// 将以前的 Orax_prjName 格式修改为 Ora_prjName格式整个作为前缀而仅仅是“_”号前面的作为前缀
			//conf_prefix=conf_prefix.substring( 0, conf_prefix.indexOf("_") );
		}
		
//			projectCode=(projectCode==null)?"":(projectCode+".");
		//System.out.println ("current project code is "+conf_prefix);

		log.debug("projectCode = " + projectCode );
		String dbType=prjBean.getDbType();   //pro.getProperty( conf_prefix+"dbType");
		String poolName=prjBean.getPoolName();  //pro.getProperty( conf_prefix+"poolName");	//连接池名称
		String dbName=prjBean.getDbName();  //pro.getProperty( conf_prefix+"dbName");	//数据库名称，只有root连接MySQL时使用
		String tableCondition= prjBean.getTableCondition();  //pro.getProperty( conf_prefix+"tableCondition");
		String path= prjBean.getExpPath();  //pro.getProperty( conf_prefix+"expPath");
		
		if(tableCondition==null || tableCondition.trim().equals("")){
			tableCondition="1=1" ;
		}
		log.info("projectCode="+projectCode + "\n" +
				  "dbType="+dbType + "\n" +
				  "poolName="+poolName + "\n" +
				  "tableCondition="+tableCondition+ "\n" +
				  "generate files to Create.:"+path);
		if(path==null || path.trim().equals("")){
			System.out.println ("user default path");
			path="E:/ProgramXP/test" ;
		} 
		StringBuffer sb_mls = new StringBuffer();
		
		//创建数据库连接
		String sql ;
		Connection conn = null ;
		Statement  stmt  = null ; 
		ResultSet  rs1 =null; 
		String[] fileNames=null;
		try{ 
			conn = ApplicationContext.getInstance().getDataSourceManager().getConnection( poolName );
			String username=conn.getMetaData().getUserName();
			
			// _____________________以上代码获取数据库连接，无论是JDBC还是ODBC。
			stmt = conn.createStatement() ;					//a can't scroll stmt
			 
			//根据不同的数据库类型结构设置不同sql
			
			// Oracle数据库采用的是GB2312的编码，MySQL采用的是utf-8的编码。
			log.debug("dbType = " + dbType );
			DatabaseDictionary dd = null;
			if(dbType.equals("oracle")){
				dd = new OracleDatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("sqlServer")){
				dd = new SqlServerDatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("sqlServer2005")){
				dd = new SqlServer2005DatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("mySQL")){
				dd = new MySqlDatabaseDictionary();
				
			}else{
				addErrors("cann't create a select statement for some type database!");
				this.saveError(request);
				return mapping.findForward("fail");					
			}
 
			sql = dd.createSqlOfTableInforByCondition(tableCondition);
			
			log.debug("sql="+sql);
			rs1 = stmt.executeQuery(sql);
			String tableEn="",tableCh="",tableType="",tableId="" ;
			String colsComment= "" ;
			File objFile = null;
			java.io.PrintWriter pw  ;
			boolean hasRecorder=false;
			int ordby = 0;
			moduleList = new ArrayList<HashMap<String,String>>();
			// loop the tables
			while(rs1.next()){  //循环所有表
				//System.out.println ("get 1");
				hasRecorder = true;
				colsComment= "";
				tableEn = rs1.getString("TABLE_NAME") ;
				tableCh = rs1.getString("COMMENTS") ;
				tableType = rs1.getString("TABLE_TYPE") ;
				if(dbType.equalsIgnoreCase("sqlServer") )
					tableId=rs1.getString("tblId") ;
		
				tableEn = (tableEn==null)?"":tableEn.trim() ;
				tableCh = (tableCh==null)?"":tableCh.trim() ;
				tableType = (tableType==null)?"":tableType.trim() ;	

				if( dbType.endsWith("mySQL") ) {
					//tableCh = StringUtils.toGB2312( tableCh );	// 乱码问题处理，可能是PowerDesigner 建表引起的
				
					//System.out.println(tableCh + "\n" + StringUtils.toGB2312( tableCh ) );
				}
				 
				if( tableCh.indexOf(";")>-1 
						|| tableCh.indexOf(":")>-1 
						|| tableCh.indexOf("\\")>-1
						|| tableCh.indexOf("\"")>-1
						|| tableCh.indexOf("/")>-1
						|| tableCh.indexOf("?")>-1
						|| tableCh.indexOf("*")>-1
						|| tableCh.indexOf("<")>-1
						|| tableCh.indexOf(">")>-1 
						|| tableCh.indexOf("\n")>-1 ) {
					//log.fatal("********* 严重警告，表的命名包含非法字符：" + tableCh );
					int t_pos = tableCh.length() ;
					
					if( tableCh.indexOf(";")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf(";") ); 
					
					if( tableCh.indexOf(":")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf(":") );
				
					if( tableCh.indexOf("\\")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("\\") );

					if( tableCh.indexOf("\"")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("\"") );
					
					if( tableCh.indexOf("/")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("/") );

					if( tableCh.indexOf("?")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("?") );

					if( tableCh.indexOf("*")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("*") );

					if( tableCh.indexOf("<")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("<") );
					
					if( tableCh.indexOf(">")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf(">") );

					if( tableCh.indexOf("\n")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("\n") );
					

					log.info("********* 严重警告，表的命名包含非法字符：" + tableCh + "。 修改为：" +tableCh.substring( 0, t_pos ).trim()  );
					if(t_pos>32){ // wzw 太长的表说明进行截取
						t_pos=32;  
					}
					tableCh = tableCh.substring( 0, t_pos ).trim() ;
				}
				
				//对表过滤，去掉视图和日志表。  wzw on 2006-10-14 ,添加视图导出
				if( tableType.equals("TABLE") ){
					tableCh = (tableCh.equals(""))?"XX表":tableCh ;

				}else if( tableType.equals("VIEW") ){
					tableCh = (tableCh.equals(""))?"XX视图":tableCh ;
				
				}
				
				//根据表名，生成folder,moduleName , t?_父模块_子模块
				String moduleName = tableEn;    //子模块名
				String folder = "mudule";							  //父模块名
//				if( moduName.indexOf("_") >0 ){
//					moduName = moduName.substring( moduName.indexOf("_")+1 );
//					if( moduName.indexOf("_") >0 ){
//						folder = moduName.substring( 0, moduName.indexOf("_") ).toLowerCase();
//						moduName = moduName.substring( moduName.indexOf("_")+1 );
//					}
//				}
				Integer nameOffset = prjBean.getTableModuleNameOffset();
				//System.out.println("nameOffset = "+nameOffset + " , moduleName 0= "+moduleName);
				//父模块名
				if( moduleName.indexOf("_") >0 ){
					System.out.println("moduleName 1= "+moduleName);
					for(int i=0; i<nameOffset; i++){
						moduleName = moduleName.substring( moduleName.indexOf("_")+1 );
					}
					if( moduleName.indexOf("_") >0 ){
						folder = moduleName.substring( 0, moduleName.indexOf("_") ).toLowerCase();
						moduleName = moduleName.substring( moduleName.indexOf("_")+1 );
					}
				}
				
				//根据表说明，生成模块说明
				String moduLabel = tableCh;
				if( moduLabel!=null && moduLabel.endsWith("表") ){
					moduLabel = moduLabel.substring(0, moduLabel.length()-1);
				}

				SmartCodeStyle scs = new SmartCodeStyle();
				sb_mls.append(tableEn).append("@")
							.append(tableCh).append("@")
							.append( scs.formatClassName(moduleName) ).append("@")
							.append(moduLabel).append("@")
							.append(folder.toLowerCase()).append("@")
							.append("$");
				
				HashMap<String,String> map = new HashMap<String,String>();
				map.put("moduleUri", "/"+folder.toLowerCase()+"/" + scs.formatObjectName(moduleName));
				map.put("moduleCode", scs.formatObjectName(moduleName) );
				map.put("moduleName", moduLabel );
				map.put("sysCode", prjBean.getAppCode() );//projectCode );
				map.put("parentCode", folder.toLowerCase() );
				map.put("ordby", "" + ordby++ );
				map.put("tableEn", tableEn );
				map.put("tableCh", tableCh );
				moduleList.add(map);
				//"item.module_code","item.module_name","item.sys_code",
			    //   "item.module_uri","item.parent_code","item.ordby"
			}
			
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			wzw.util.DbUtils.closeQuietly(rs1); 
			wzw.util.DbUtils.closeQuietly(stmt); 
			wzw.util.DbUtils.closeQuietly(conn);
		}
		try {
			if(sb_mls.toString().endsWith("$")){
				sb_mls.deleteCharAt( sb_mls.length()-1 );
			}
			System.out.println( "------"+sb_mls );
			response.setContentType("text/plain; charset=gbk");
			response.getWriter().print(sb_mls.toString() );
			
		} catch (Exception e) { 
			e.printStackTrace();
		}
		return null;
			
	}
	
	/**
	 * 创建表文件。 该类要求线程安全。 action的默认行为。
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public synchronized ActionForward createTableFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
	
		//清除现有的错误提示信息
		clearErrors();
		//版权保护-copyright protect here
		String serverLoginName=System.getProperty("user.name");
		// 2008-11-24,取消验证，以后可以增加上来
		if(false && !( serverLoginName.equalsIgnoreCase("WUZEWEN")	
		    ||serverLoginName.equalsIgnoreCase("WZWEN")
		    ||serverLoginName.equalsIgnoreCase("Zewin")
		    ||serverLoginName.equalsIgnoreCase("Zeven")
		    ||serverLoginName.equalsIgnoreCase("Administrator") )){
			addErrors("err.illegalAuthorization");
			this.saveError(request);
			return mapping.findForward("fail");	
		} 
		
		//
		createTableFile(mapping, request, response);
		
		return mapping.findForward("success");
		
	}

	protected synchronized ActionForward createTableFile(ActionMapping mapping,  HttpServletRequest request, HttpServletResponse response) {

    	// 变量定义
		StringBuffer sbf = new StringBuffer();
		String dbType = "" ;	//数据库类型
		String driver = "" ;	//驱动类
		String url = "" ;		//连接url属性
		String username="";		
		String password="";
		String maxconn="";		//最大连接数
		String poolName="";		//
		String path="" ;		//导出的sql文件woo.table存放路径
		String tableCondition="";	//表的特征条件
		String is_tblname="";	//表名
		String dbName="";	//数据库名称，针对MySQL使用root连接
		String columns = request.getParameter("columns");
		//if (columns!=null && columns.trim().length()>0) {
		//	columns = "@"+columns.toLowerCase()+"@";
		//}else{
			columns=null;
		//}
		
		//获取request参数信息和配置文件值
		is_tblname = request.getParameter("table0");
		if (is_tblname==null) {
			is_tblname = request.getParameter("tblName");
		}
		
		try
		{			
			//获取prefix信息
			String projectCode=request.getParameter("projectCode");	//从客户端取编号
			
			CompanyBean comanpyBean = new CompanyBean();
			ProjectBean prjBean = PdaContext.getProjectMap().get(projectCode);
			log.debug("projectCode = " + projectCode );
			data.put("project", prjBean);
			data.put("company", comanpyBean);
			comanpyBean.setCode(prjBean.getCompanyCode());
			comanpyBean.setName(prjBean.getCompanyName());
			
			//System.out.println ("aa"+conf_prefix);
			if(projectCode==null || projectCode.trim().equals("null") || projectCode.trim().equals("")){
				//System.out.println ("faddd");
				projectCode= "cannotFind";
			}else{
				// 将以前的 Orax_prjName 格式修改为 Ora_prjName格式整个作为前缀而仅仅是“_”号前面的作为前缀
				//conf_prefix=conf_prefix.substring( 0, conf_prefix.indexOf("_") );
			}
			
//			projectCode=(projectCode==null)?"":(projectCode+".");
			//System.out.println ("current project code is "+conf_prefix);

			log.debug("projectCode = " + projectCode );
			dbType=prjBean.getDbType();   //pro.getProperty( conf_prefix+"dbType");
			poolName=prjBean.getPoolName();  //pro.getProperty( conf_prefix+"poolName");	//连接池名称
			dbName=prjBean.getDbName();  //pro.getProperty( conf_prefix+"dbName");	//数据库名称，只有root连接MySQL时使用
			//username=pro.getProperty( conf_prefix+"username");
			//driver=pro.getProperty( conf_prefix+"driver");
			//url=pro.getProperty( conf_prefix+"url");
			//password=pro.getProperty( conf_prefix+"password");
			//maxconn=pro.getProperty( conf_prefix+"maxconn");
			tableCondition= prjBean.getTableCondition();  //pro.getProperty( conf_prefix+"tableCondition");
			path= prjBean.getExpPath();  //pro.getProperty( conf_prefix+"expPath");
			
			if(tableCondition==null || tableCondition.trim().equals("")){
				tableCondition="1=1" ;
			}
			log.info("projectCode="+projectCode + "\n" +
					  "dbType="+dbType + "\n" +
					  "poolName="+poolName + "\n" +
					  "tableCondition="+tableCondition+ "\n" +
					  "generate files to Create.:"+path);
			if(path==null || path.trim().equals("")){
				System.out.println ("user default path");
				path="E:/ProgramXP/test" ;
			}
			java.io.File file = new java.io.File( path );
			if(!file.exists()){
				file.mkdirs();		//多级目录创建
				System.out.println("create path success,path is"+path);
			}
		}catch( Exception e){
			this.addErrors( e.getMessage());
			this.saveError(request);
			System.out.println ( e.getMessage());
			return mapping.findForward("fail");
		}
		
		//创建数据库连接
		String sql ;
		Connection conn = null ;
		Statement  stmt  = null ;
		Statement  stmt2  = null ;
		Statement  stmt3  = null ;
		ResultSet  rs1 =null;
		ResultSet  rs2 =null;
		ResultSet  rs3 =null;
		String[] fileNames=null;
		try{
			//得到数据库连接
			//Class.forName(driver) ;
			//conn = DriverManager.getConnection(url, username, password) ;
			//------------------ 演示如何调用 dao对象：
//			CreateTableFileDao ctfd = new CreateTableFileDaoImpl();
//			ctfd.getTableInforByName(poolName, tableCondition);
//			ctfd.getTableInforByCondition(poolName, dbName, is_tblname);
			//------------------ End of 演示如何调用 dao对象
			
			conn = ApplicationContext.getInstance().getDataSourceManager().getConnection( poolName );
			username=conn.getMetaData().getUserName();
			//System.out.println ("dfafdsf===u "+username);
			//if( testResultSet(conn) ) return ;			
			// _____________________以上代码获取数据库连接，无论是JDBC还是ODBC。
			stmt = conn.createStatement() ;					//a can't scroll stmt
			stmt2 = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY) ;
			stmt3 = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY) ;
			
			//根据不同的数据库类型结构设置不同sql
			
			// Oracle数据库采用的是GB2312的编码，MySQL采用的是utf-8的编码。
			log.debug("dbType = " + dbType );
			DatabaseDictionary dd = null;
			if(dbType.equals("oracle")){
				dd = new OracleDatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("sqlServer")){
				dd = new SqlServerDatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("sqlServer2005")){
				dd = new SqlServer2005DatabaseDictionary();
				
			}else if(dbType.equalsIgnoreCase("mySQL")){
				dd = new MySqlDatabaseDictionary();
				
			}else{
				addErrors("cann't create a select statement for some type database!");
				this.saveError(request);
				return mapping.findForward("fail");					
			}

			log.debug("is_tblname="+is_tblname);
			if(is_tblname==null||is_tblname.trim().equals("")){
				sql = dd.createSqlOfTableInforByCondition(tableCondition);
				
			}else{
				is_tblname = is_tblname.trim(); //notBlank情况去空格
				sql = dd.createSqlOfTableInforByName( dbName, is_tblname);
				
			}

			log.debug("sql="+sql);
			rs1 = stmt.executeQuery(sql);
			String tableEn="",tableCh="",tableType="",tableId="" ;
			String colsComment= "" ;
			File objFile = null;
			java.io.PrintWriter pw  ;
			boolean hasRecorder=false;
			// loop the tables

			while(rs1.next()){  //循环所有表
				//System.out.println ("get 1");
				hasRecorder = true;
				colsComment= "";
				tableEn = rs1.getString("TABLE_NAME") ;
				tableCh = rs1.getString("COMMENTS") ;
				tableType = rs1.getString("TABLE_TYPE") ;
				if(dbType.equalsIgnoreCase("sqlServer") || dbType.equalsIgnoreCase("sqlServer2005") )
					tableId=rs1.getString("tblId") ;
		
				tableEn = (tableEn==null)?"":tableEn.trim() ;
				tableCh = (tableCh==null)?"":tableCh.trim() ;
				tableType = (tableType==null)?"":tableType.trim() ;	

				if( dbType.endsWith("mySQL") ) {
					//tableCh = StringUtils.toGB2312( tableCh );	// 乱码问题处理，可能是PowerDesigner 建表引起的
				
					//System.out.println(tableCh + "\n" + StringUtils.toGB2312( tableCh ) );
				}
				 
				if( tableCh.indexOf(";")>-1 
						|| tableCh.indexOf(":")>-1 
						|| tableCh.indexOf("\\")>-1
						|| tableCh.indexOf("\"")>-1
						|| tableCh.indexOf("/")>-1
						|| tableCh.indexOf("?")>-1
						|| tableCh.indexOf("*")>-1
						|| tableCh.indexOf("<")>-1
						|| tableCh.indexOf(">")>-1 
						|| tableCh.indexOf("\n")>-1 ) {
					//log.fatal("********* 严重警告，表的命名包含非法字符：" + tableCh );
					int t_pos = tableCh.length() ;
					
					if( tableCh.indexOf(";")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf(";") ); 
					
					if( tableCh.indexOf(":")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf(":") );
				
					if( tableCh.indexOf("\\")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("\\") );

					if( tableCh.indexOf("\"")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("\"") );
					
					if( tableCh.indexOf("/")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("/") );

					if( tableCh.indexOf("?")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("?") );

					if( tableCh.indexOf("*")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("*") );

					if( tableCh.indexOf("<")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("<") );
					
					if( tableCh.indexOf(">")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf(">") );

					if( tableCh.indexOf("\n")>-1 )
						t_pos = Math.min( t_pos ,tableCh.indexOf("\n") );
					

					log.info("********* 严重警告，表的命名包含非法字符：" + tableCh + "。 修改为：" +tableCh.substring( 0, t_pos ).trim()  );
					if(t_pos>32){ // wzw 太长的表说明进行截取
						t_pos=32;  
					}
					tableCh = tableCh.substring( 0, t_pos ).trim() ;
				}
				
				//对表过滤，去掉视图和日志表。  wzw on 2006-10-14 ,添加视图导出
				if( tableType.equals("TABLE") ){
					tableCh = (tableCh.equals(""))?"XX表":tableCh ;

				}else if( tableType.equals("VIEW") ){
					tableCh = (tableCh.equals(""))?"XX视图":tableCh ;
				
				}else{
					continue ;
				}

				//if(tableEn.trim().endsWith("_H"))	//针对于cswater系统日志表改为在where 条件中过滤
				//	continue ; 
				//判断该表的文件是否存在，删除同表名的，只需要一个，
				//不能一开始就删除，避免后来导出失败，而是导一个删除一个
				objFile = new java.io.File(path);
				fileNames=objFile.list();
				File[] files = objFile.listFiles();
				for(int k=0;k<fileNames.length;k++){
					if(fileNames[k].toLowerCase().startsWith(tableEn.toLowerCase()+"___")){ //wzw:统一转为小写比较
						files[k].delete();
						//objFile=new File(path +File.separator+ fileNames[k]);
						//objFile.delete();
						//break; 可能有多个，这里循环较多，表数量的平方
					}
				}

				DatabaseTableBean tableBean = new DatabaseTableBean();
				tableBean.setName(tableEn);
				tableBean.setLabel( DbUtils.getLabelByComment(tableCh) );  
				tableBean.setComment(tableCh);
				tableBean.setId(tableId);
				tableBean.setType(tableType);
				data.put("table", tableBean);
				
				///////////////// 生成模块信息
				
				//根据表名，生成folder,moduleName , t?_父模块_子模块
				String moduName = tableEn;    //子模块名
				String moduLabel = tableCh;
				String folder = "mudule";							  //父模块名
				if( moduName.indexOf("_") >0 ){
					moduName = moduName.substring( moduName.indexOf("_")+1 );
					if( moduName.indexOf("_") >0 ){
						folder = moduName.substring( 0, moduName.indexOf("_") ).toLowerCase();
						moduName = moduName.substring( moduName.indexOf("_")+1 );
					}
				}
				//根据表说明，生成模块说明
				if( moduLabel!=null && moduLabel.endsWith("表") ){
					moduLabel = moduLabel.substring(0, moduLabel.length()-1);
				} 

				SmartCodeStyle scs = new SmartCodeStyle();
				data.put("module", this.moduleBean);
				this.moduleBean.setLabel(moduLabel);
				this.moduleBean.setName( scs.formatObjectName(moduName) );
				if(folder!=null && folder.startsWith("/")){
					folder = folder.substring(1);
				}
				this.moduleBean.setFolder(folder);
//				map.put("moduleUri", "/"+folder.toLowerCase()+"/" + scs.formatObjectName(moduName));
//				map.put("moduleCode", scs.formatObjectName(moduName) );
//				map.put("moduleName", moduLabel );
//				map.put("sysCode", prjBean.getAppCode() );//projectCode );
//				map.put("parentCode", folder.toLowerCase() );
//				map.put("ordby", "" + ordby++ );
//				map.put("tableEn", tableEn );
//				map.put("tableCh", tableCh );
				///////////////// 生成模块信息 end
				
				
				objFile = new java.io.File(path +File.separator+tableEn+"___"+tableCh+".woo.table" );
				log.info("createNewFile="+path +File.separator+tableEn+"___"+tableCh+".woo.table" );
//				try {	
				
					objFile.createNewFile()  ;
					
//				}catch(IOException ioe) {
//					try {
//						tableCh = StringUtils.toGB2312( tableCh );//new String( tableCh.getBytes("utf-8"),"gb2312");
//						objFile = new java.io.File(path+tableEn+"___"+tableCh+".woo.table" );	
//						objFile.createNewFile()  ;
//					}catch(IOException ioe2) {
//						objFile = new java.io.File(path+tableEn+"___XY表.woo.table" );	
//						objFile.createNewFile() ; 
//						
//					}
//				}
				pw = new java.io.PrintWriter(new java.io.FileOutputStream(objFile)) ;
				//pw = new PrintWriter(new FileOutputStream( objFile ));
					//clean up
		
				/////////////////////////////////////////////////////////////
				String tableMkbh ="";
				pw.println("-- this sql script is created by PDA(Java),WUZEWEN on "+( new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date() ) )+",DBMS is "+dbType ) ;
				//pw.println("-- this sql script is created by DA(Java),WUZEWEN on "+(new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date() ) ) ) ;
				pw.println("drop table "+tableEn) ;
				pw.println(";" ) ;
				pw.println("create table "+tableEn + "\t\t\t/* "+((tableMkbh=="")?(""):("["+tableMkbh+"]"))+"Table Name:"+ toOneRow(tableCh)+" */" ) ;
				pw.println( "(" ) ;
								
				int key_tab = 4 ;		//设置一个tab为 4个英文字,col01为 1*key_tab, col01为 2*key_tab
				String spe01="\t",spe02="\t" ,spe03="\t" ;
				//String colsComment="" ;
				String colName,colType,colComm,col04,col05 ;
				int isAutoIncrement;
				DatabaseColumnBean autoIncrementColumn = null;
				
				//rs2 = stmt2.executeQuery("select t.COLUMN_NAME,t.DATA_TYPE,t.DATA_LENGTH,t.DATA_PRECISION,t.DATA_SCALE,t.NULLABLE,t.COLUMN_ID,t2.comments from user_tab_columns t ,user_col_comments t2 where t.TABLE_NAME=t2.table_name and t.COLUMN_NAME=t2.column_name and (t.TABLE_NAME like 'FX%' or t.TABLE_NAME like 'ST%' ) and t.TABLE_NAME='"+tableEn+"' order by t.column_id");
				
				sql = dd.createSqlOfColumnInforByCondition(dbName, tableId, tableEn );
				
				
				rs2 = stmt2.executeQuery(sql);
				//System.out.println(sql);
				int allCount = 0 ,count =0 ;
				rs2.last() ;
				allCount = rs2.getRow() ;
				rs2.beforeFirst() ;
				// loop the table's columns
				//System.out.println ( tableEn );
					
				while( rs2.next() ){   //循环表的所有列
					//System.out.println("En=  7" );
					//String spe01="",spe02="",spe03="" ;
					//获取列
					count++ ;
					colName = rs2.getString("COLUMN_NAME");
					colType = rs2.getString("typefull");	//DATA_TYPE			
					colComm = rs2.getString("COMMENTS");
					col05   = rs2.getString("NULLABLE");
					isAutoIncrement   = rs2.getInt("isAutoIncrement");
					
					//System.out.println("En=  7" );
					//col04 = tablecols04.substring( m2 , m1).trim();
					if(colName==null || colType==null ) 
						continue ;
						
					colName = colName.trim().toLowerCase();
					colType = colType.trim();
					colComm = (colComm==null)?"":colComm.trim();
					if( dbType.endsWith("mySQL") ) {		// 乱码问题处理，可能是PowerDesigner 建表引起的
						//colComm = StringUtils.toGB2312( colComm );
					}  
					// 不用编码，使用PD建表采需要编码。使用MySQL官方工具和EMS都不需要处理
					// 数据库里面内容的编码与数据库、表指定的编码一致就行，无论采用GBK,UTF-8，程序取出来的内容都不需要编码转换
					
					col04 = (col05.equals("Y"))?"(uncheck)":"(check)" ;
					col05   = (col05.equals("Y"))?"null":"not null";				
					
					String colLength="128";
					if (colType.indexOf("(")>-1) {   //colType:  varchar(12),number(8,2).
						int endPos = colType.indexOf(","); //优先
						if (endPos<0) {
							endPos = colType.indexOf(")");
						}
						colLength = colType.substring(colType.indexOf("(")+1, endPos );
					}
					//只有选中的才加入到模型对象中
					if (columns==null
							|| columns.indexOf("@"+colName+"@")>-1) {
						DatabaseColumnBean colBean = new DatabaseColumnBean();
						colBean.setName(colName);
						colComm = setExtProperties(colBean, colComm ); //设置扩展属性并移除
						colBean.setLabel( DbUtils.getLabelByComment(colComm) );  //默认label与comment相同
						colBean.setComment(colComm);
						colBean.setType(colType);
						colBean.setLength(colLength);
						colBean.setNullable(col05);
						colBean.setIsAutoincrement(isAutoIncrement);
						tableBean.getColumns().add(colBean);
						//if(isAutoIncrement<1){  //非自增
						//}
						if(isAutoIncrement>0){//自增列，non-insert,non-update
							autoIncrementColumn = colBean;  //本表的自动增长列名，Mysql自动为主键
							colBean.setReadOnly("1");
							colBean.setRequired("0");

							//对于MySql,SqlServer，预先设置好,重复设置则覆盖
							List<DatabaseColumnBean> indexColList = new ArrayList<DatabaseColumnBean>();
							indexColList.add(colBean);
							tableBean.setPrimaryKey( indexColList );
							//tableBean.getInsertColumns().removeAll(indexColList); //移除主键列，主键列不更新
							//tableBean.getUpdateColumns().removeAll(indexColList); //移除主键列，主键列不更新
							
						}else{
							tableBean.getInsertColumns().add(colBean);
							tableBean.getUpdateColumns().add(colBean);  //更新列=所有列-主键列
						}
					}
					
					//System.out.println("En=  7" );
					if(colName.length()< key_tab)
						spe01 = "\t\t\t" ;
					else if(colName.length()< 2*key_tab)
						spe01 = "\t\t" ;
					else if(colName.length()< 3*key_tab)
						spe01 = "\t" ;
					else
						spe01 = "\t" ;
			
					if(colType.length()<key_tab)
						spe02 = "\t\t\t\t" ;
					else if(colType.length()<2*key_tab)
						spe02 = "\t\t\t" ;
					else if(colType.length()<3*key_tab)
						spe02 = "\t\t" ;
					else if(colType.length()<4*key_tab)
						spe02 = "\t" ;
					else
						spe02 = "\t" ;
			
					if(col05.length()< key_tab)
						spe03 = "\t\t\t" ;
					else if(col05.length()< 2*key_tab)
						spe03 = "\t\t" ;
					else if(col05.length()< 3*key_tab)
						spe03 = "\t" ;
					else
						spe03 = "\t" ;
					
//					if(isAutoIncrement>0){
//						autoIncrementColumn = colBean;  //本表的自动增长列名，Mysql自动为主键
//					}
					//log.println("\t"+colName + spe01 +colType+ spe02 +col05+ (count<allCount?",":"") +spe03 + "/* "+colComm+col04 +" */" );
					pw.println( "\t"+colName + spe01 +colType+ spe02 +col05
									+ (isAutoIncrement>0?" AUTO_INCREMENT":"") 
									+ ((count>=allCount&&autoIncrementColumn==null)?"":",") 
									+spe03 + "/* "+ toOneRow(colComm+col04) +" */"); 
					//列注释信息
					if(dbType.equalsIgnoreCase("oracle")){
						colsComment += "comment on column "+ tableEn +"."+ colName + "		is '" + colComm + "';@@@" ;
					}else if(dbType.equalsIgnoreCase("sqlserver")){
						colsComment += "exec sp_addextendedproperty 'MS_Description', '"+ colComm +"', 'user', '"+ username + "', 'table', '" + tableEn + "', 'column', '"+colName+"';@@@" ;
					}		
					//System.out.println("En=  7" );
				}
				if(autoIncrementColumn!=null){ //mysql自增长列处理
					pw.println( "\t PRIMARY    KEY ("+autoIncrementColumn.getName()+")" ) ;
				}
				pw.println( ")" ) ;
				pw.println( ";" ) ;
				
				//主键和索引、外键
				////////////////////////////////////
				if(dbType.equalsIgnoreCase("oracle") ){
					//StringBuffer sbf=new StringBuffer();
					sbf.delete(0, sbf.length());
					sbf.append(" Select t.Index_Name, t.Index_Type, t.Table_Owner")
						.append(" ,t.Table_Name, t.Table_Type, t.Uniqueness")
						.append(" ,t.Generated")
						.append(" From User_Indexes t")
						.append(" Where t.Table_Type = 'TABLE'")
						.append(" And Table_Name = '"+tableEn+"'");
					log.debug(sbf);
					rs2 = stmt2.executeQuery(sbf.toString());// order by t.generated desc
					allCount = 0;
					count =0 ;
					// loop the table's index
					//System.out.println ("select t.index_name,t.index_type,t.table_owner,t.table_name,t.table_type,t.uniqueness,t.generated from user_indexes t where t.table_name= 'DEMOTABLE' and t.table_type='TABLE' where table_name='"+tableEn+"' order by t.generated desc");
					String index_name="",index_type="",uniqueness="",generated="";
					while( rs2.next() ){
							
						index_name = rs2.getString("index_name") ;
						index_type = rs2.getString("index_type") ;
						uniqueness = rs2.getString("uniqueness") ;
						generated = rs2.getString("generated") ;
						if( index_type.trim().equals("LOB")){			//BLOB字段,Orale自动建立一个LOB类型的索引，不用管
							continue ;
						}
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Index_Name, t.Table_Name, t.Column_Name")
							.append(" ,t.Column_Position")
							.append(" From User_Ind_Columns t")
							.append(" Where t.Index_Name = '"+index_name+"'")
							.append(" Order By t.Column_Position Asc");
						log.debug(sbf);
						rs3 = stmt3.executeQuery(sbf.toString());
						String str_indexCols ="";
						List<DatabaseColumnBean> indexColList = new ArrayList<DatabaseColumnBean>();
						List<DatabaseColumnBean> t_cols = tableBean.getColumns();
						while (rs3.next()){
							String t_cName = rs3.getString("column_name");
							str_indexCols += t_cName + "," ;
							
							for (DatabaseColumnBean bean : t_cols) {
								if (t_cName.equalsIgnoreCase(bean.getName())) {
									indexColList.add(bean );
									break;
								}
							}
						}
						
						str_indexCols = str_indexCols.trim();
						str_indexCols = str_indexCols.substring(0, str_indexCols.length()-1 ) ;
						//System.out.println ("type="+ index_type);
						if( index_type.trim().equals("BITMAP") ){		//bitmap index
							pw.println("create bitmap index "+index_name.toLowerCase()+" on "+tableEn+"(" +str_indexCols+ ")" ) ;
							pw.println(";");
						}else if( index_type.trim().equals("DOMAIN") ){	//context index
							//create index ctx_FX_XT_DOCAFFIX on FX_XT_DOCAFFIX(BCON) indextype is ctxsys.context parameters ('lexer water.cnlex');
							//全文索引使用不多，建立和维护工作较多，在此仅做提示性说明
							pw.println("-- ignore a context index here");
						}else if(index_name.endsWith("_PK")||index_name.startsWith("PK_") ){			//primary key //generated.equals("Y")
							pw.println("alter table "+tableEn+" add constraint PK_"+tableEn+" primary key (" +str_indexCols+ ")" ) ;
							pw.println(";");
							if (indexColList.size()>0) {
								tableBean.setPrimaryKey(indexColList);
								//tableBean.getInsertColumns().removeAll(indexColList);
								tableBean.getUpdateColumns().removeAll(indexColList); //移除主键列，主键列不更新
							}
						}else if( uniqueness.equals("UNIQUE") ){		//unique index
							pw.println("create unique index "+index_name.toLowerCase()+" on "+tableEn+"(" +str_indexCols+ ")" ) ;
							pw.println(";");
						}else if( uniqueness.equals("NONUNIQUE") ){	//normal index
							pw.println("create index "+index_name.toLowerCase()+ " on "+tableEn+"(" +str_indexCols+ ")" ) ;
							pw.println(";");
						}else{			//else index 不处理
							pw.println("-- ignore a index here");
						}
					}
					
					//外键 wzw on 2005-09-26 StringBuffer sbf=new StringBuffer();
					sbf.delete(0, sbf.length());
					sbf.append(" Select Constraint_Name, r_Constraint_Name")
						.append(" From User_Constraints t")
						.append(" Where Owner = '"+username.toUpperCase()+"'")
						.append(" And Table_Name = '"+tableEn+"'")
						.append(" And (Constraint_Type = 'R')");
					log.debug(sbf);
					rs2 = stmt2.executeQuery(sbf.toString());// order by t.generated desc
					String cons_name="",rcons_name="";
					String writeStr="";
					while( rs2.next() ){
						writeStr="";
						//本表的列
						cons_name=rs2.getString("CONSTRAINT_NAME");
						writeStr="alter table "+tableEn+" add constraint "+cons_name;
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Column_Name")
							.append(" From User_Cons_Columns t")
							.append(" Where Owner = '"+username.toUpperCase()+"'")
							.append(" And Constraint_Name = '"+cons_name+"'");
						log.debug(sbf);
						rs3 = stmt3.executeQuery( sbf.toString() );
						String indexColList ="";
						while (rs3.next()){
							indexColList += rs3.getString("column_name") + "," ;
						}
						indexColList = indexColList.trim();
						indexColList = indexColList.substring(0, indexColList.length()-1 ) ;
						writeStr+=" foreign key ("+indexColList+")";
						//指向的表和列---其实都是根据约束名找列信息，此处同时要获取表名
						String l_tbl_name="";
						indexColList="";
						cons_name=rs2.getString("R_CONSTRAINT_NAME");
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Table_Name, t.Constraint_Name, t.Column_Name")
							.append(" From User_Cons_Columns t")
							.append(" Where Owner = '"+username.toUpperCase()+"'")
							.append(" And Constraint_Name = '"+cons_name+"'");
						log.debug(sbf);
						rs3 = stmt3.executeQuery(sbf.toString());
						while (rs3.next()){
							l_tbl_name=rs3.getString("table_name");
							indexColList += rs3.getString("column_name") + "," ;
						}
						indexColList = indexColList.trim();
						indexColList = indexColList.substring(0, indexColList.length()-1 );
						writeStr+=" references "+l_tbl_name+"("+indexColList+") ";
						pw.println(writeStr);
						pw.println(";");
					}
					
				}else if(dbType.equalsIgnoreCase("mySQL")){ //mysql 获取主键,外键信息
					
					// ALTER TABLE `wzw_mysql_db`.`demotable` ADD PRIMARY KEY (`ID`);
					// ALTER TABLE demotablevvADD UNIQUE INDEX Index_2(XSSH);
					String tmp_sql = dd.createSqlOfConstraints(dbName, tableEn);
					rs2 = stmt2.executeQuery(tmp_sql);
					allCount = 0;
					count =0 ;
					String constraint_type = null;
					String constraint_name = null ;
					String constraint_name_strs = "" ;
					List<DatabaseColumnBean> indexColList = new ArrayList<DatabaseColumnBean>();
					while( rs2.next() ){
						constraint_type = rs2.getString("constraint_type"); //类型
						constraint_name = rs2.getString("constraint_name"); //名称
						constraint_name_strs = "";
						tmp_sql = dd.createSqlOfConstraintColumns(dbName, tableEn, constraint_name);
						rs3 = stmt3.executeQuery(tmp_sql); //列信息						
						List<DatabaseColumnBean> t_cols = tableBean.getColumns();
						while (rs3.next()) {
							String t_cName = rs3.getString("COLUMN_NAME");
							constraint_name_strs += t_cName+",";
							
							for (DatabaseColumnBean bean : t_cols) {
								if (t_cName.equalsIgnoreCase(bean.getName())) {
									indexColList.add(bean );
									break;
								}
							}
						}
						
						constraint_name_strs = constraint_name_strs.substring(0, constraint_name_strs.length()-1);
						
						if (constraint_type.toLowerCase().indexOf("primary key")>-1) {
							if(autoIncrementColumn!=null){ //自增长列，以及写入sql了
								continue;
							}
							pw.println("ALTER TABLE "+tableEn
									+" ADD PRIMARY KEY ( "+constraint_name_strs+" )" ) ;
							pw.println(";");
							
						}else if (constraint_type.toLowerCase().indexOf("unique")>-1) {
							pw.println("ALTER TABLE "+tableEn
									+" ADD UNIQUE INDEX "
									+constraint_name+" ( "+constraint_name_strs+" )" ) ;
							pw.println(";");
						}
					}
					if (indexColList.size()>0) {
						tableBean.setPrimaryKey(indexColList);
						//tableBean.getInsertColumns().removeAll(indexColList); //移除主键列，主键列不更新
						tableBean.getUpdateColumns().removeAll(indexColList); //移除主键列，主键列不更新
					}
					
					
				}else if(dbType.equalsIgnoreCase("sqlserver") 
						|| dbType.equalsIgnoreCase("sqlserver2005") ){
					// StringBuffer sbf=new StringBuffer();
					sbf.delete(0, sbf.length());
					sbf.append(" Select t.Indid Index_Id, t.Name Index_Name From Sysindexes t")
						.append(" Where (Id = '"+tableId+"')")
						.append(" Order By t.Indid Asc");
					log.debug(sbf);
					rs2 = stmt2.executeQuery( sbf.toString() );
					allCount = 0;
					count =0 ;
					// loop the table's index
					//System.out.println ("select t.index_name,t.index_type,t.table_owner,t.table_name,t.table_type,t.uniqueness,t.generated from user_indexes t where t.table_name= 'DEMOTABLE' and t.table_type='TABLE' where table_name='"+tableEn+"' order by t.generated desc");
					String index_name="",index_id="";
					while( rs2.next() ){
							
						String t_idx_name = rs2.getString("index_name");
						if(t_idx_name==null){
							continue;
						}
						index_name = t_idx_name.trim() ;
						index_id   = rs2.getString("index_id").trim() ;
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Id, t.Indid, T2.Name")
							.append(" From Sysindexkeys t, Syscolumns T2")
							.append(" Where t.Id = '"+tableId+"'")
							.append(" And t.Indid = '"+index_id+"'")
							.append(" And t.Id = T2.Id")
							.append(" And t.Colid = T2.Colid")
							.append(" Order By t.Colid Asc");
						log.debug(sbf);
						rs3 = stmt3.executeQuery( sbf.toString() );
						if(!rs3.next()){
							continue ;		//如果没有列信息，继续
						}
						rs3.beforeFirst() ;
						String indexColList ="";
						while (rs3.next()){
							String t_name = rs3.getString("name");
							setColumnAsPrimaryKey(tableBean, tableBean.getColumns(), t_name);
							indexColList += t_name + "," ;
						}					
						indexColList = indexColList.trim();
						indexColList = indexColList.substring(0, indexColList.length()-1 ) ;
						//System.out.println ("type="+ index_type);   给所有约束都起名称
						if( index_name.toUpperCase().startsWith("PK_") ){			//primary key
							pw.println("alter table "+tableEn+" add constraint PK_"+tableEn+" primary key (" +indexColList+ ")" ) ;
							pw.println(";");
						}else if( index_name.startsWith("uni_") ){		//unique noncluster index
							pw.println("create unique nonclustered index "+index_name.toLowerCase()+" on "+tableEn+"(" +indexColList+ ")" ) ;
							pw.println(";");
						}else if( index_name.startsWith("uci_") ){		//unique cluster index
							pw.println("create unique clustered index "+index_name.toLowerCase()+" on "+tableEn+"(" +indexColList+ ")" ) ;
							pw.println(";");
						}else if( index_name.startsWith("ui_") ){		//unique index
							pw.println("create unique index "+index_name.toLowerCase()+" on "+tableEn+"(" +indexColList+ ")" ) ;
							pw.println(";");
						}else if( index_name.startsWith("i_")||index_name.startsWith("ix_") ){	//normal index
							pw.println("create index "+index_name.toLowerCase()+ " on "+tableEn+"(" +indexColList+ ")" ) ;
							pw.println(";");
						}else{							//else index 不处理
							pw.println("-- ignore a index here");
							//pw.println("create index "+index_name.toLowerCase()+ " on "+tableEn+"(" +indexColList+ ")" ) ;
							//pw.println(";");
						}
		
					}
					//外键 wzw on 2005-10-27,一个表可以有多个外键，但是最好不要两个外键对应于同一个表
					rs2 = stmt2.executeQuery("SELECT t.* FROM sysreferences t where t.fkeyid='"+tableId+"' order by t.constid desc");
					String fkeyid=tableId,rkeyid="",rTblName="";
					String writeStr="",cons_name="";
					int i=1,indexColId=0;
					String indexColList="",indexColIdList="";
					int k=1;
					while( rs2.next() ){
						i=1;
						indexColId=0;
						indexColIdList="";
						indexColList="";
						writeStr="";
						//获取reference表的信息
						rkeyid=rs2.getString("rkeyid");
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Id As Tblid, t.Name As Table_Name, 'TABLE' As Table_Type")
							.append(" From Sysobjects t")
							.append(" Where ((t.Xtype = 'U' Or t.Xtype = 'S')")
							.append(" And t.Id = '"+rkeyid+"')");
						log.debug(sbf);
						rs3 = stmt3.executeQuery(sbf.toString());
						while (rs3.next()){
							rTblName=rs3.getString("TABLE_NAME");
						}						
						
						//本表的列
						cons_name="FK_"+tableEn.toUpperCase()+"_"+rTblName.toUpperCase()+(k>1?"_"+k:"");
						writeStr="alter table "+tableEn+" add constraint "+cons_name;
						k++;
						
						//获取f表和r表的列信息
						indexColId=rs2.getInt("fkey"+ i++);
						while(indexColId>0){
							indexColIdList+=indexColId+",";
							indexColId=rs2.getInt("fkey"+ i++);							
						}
						if(indexColIdList.endsWith(",")){
							indexColIdList=indexColIdList.substring(0,indexColIdList.length()-1);
						}
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Name Column_Name, t.Colid")
							.append(" From Syscolumns t")
							.append(" Where (t.Id = '"+tableId+"')")
							.append(" And t.Colid In ("+indexColIdList+")")
							.append(" Order By t.Colid Asc");
						log.debug(sbf);
						rs3 = stmt3.executeQuery(sbf.toString());
						while (rs3.next()){
							indexColList += rs3.getString("column_name")+"," ;
						}
						if(indexColList.endsWith(",")){
							indexColList=indexColList.substring(0,indexColList.length()-1);
						}
						writeStr+=" foreign key ("+indexColList+")";
						
						//r表信息
						i=1;
						indexColId=0;
						indexColIdList="";
						indexColList="";						
						indexColId=rs2.getInt("rkey"+ i++);
						while(indexColId>0){
							indexColIdList+=indexColId+",";
							indexColId=rs2.getInt("rkey"+ i++);							
						}
						if(indexColIdList.endsWith(",")){
							indexColIdList=indexColIdList.substring(0,indexColIdList.length()-1);
						}
						//StringBuffer sbf=new StringBuffer();
						sbf.delete(0, sbf.length());
						sbf.append(" Select t.Name Column_Name, t.Colid")
							.append(" From Syscolumns t")
							.append(" Where (t.Id = '"+rkeyid+"')")
							.append(" And t.Colid In ("+indexColIdList+")")
							.append(" Order By t.Colid Asc");
						log.debug(sbf);
						rs3 = stmt3.executeQuery(sbf.toString());
						while (rs3.next()){
							indexColList += rs3.getString("column_name")+"," ;
						}
						if(indexColList.endsWith(",")){
							indexColList=indexColList.substring(0,indexColList.length()-1);
						}
						writeStr+=" references "+rTblName+"("+indexColList+") ";
						pw.println(writeStr);
						pw.println(";");					
					}		 
				
				}
	
						
				//所有注释写入文件(mysql 无需单独写注释)
				if(dbType.equalsIgnoreCase("oracle")){
					pw.println("comment on table "+ tableEn +" is '" + toOneRow(tableCh) +"';" ) ;
				}else if(dbType.equalsIgnoreCase("sqlserver")){
					pw.println("exec sp_addextendedproperty 'MS_Description', '"+ toOneRow(tableCh) +"', 'user', '"+ username + "', 'table', '" + tableEn + "';");
				}
			
				int i = 0,j=0 ;
				i = colsComment.indexOf("@@@",j ) ;
				
				while(i>0){
					if(dbType.equalsIgnoreCase("oracle")){
						pw.println( colsComment.substring(j,i) ) ;
					}else if(dbType.equalsIgnoreCase("sqlserver")){
						pw.println( colsComment.substring(j,i) ) ;
					}
					j = i + 3 ;
					i  = colsComment.indexOf("@@@",j ) ;
				}			
				//pw.println( ";" ) ;  //多余的这个提交符在sqlserver 中产生错误	
				pw.close();
			}
			
			if(!hasRecorder){
				System.out.println ("导出过程中产生错误------！");
				addErrors("err.noTableFound");
				this.saveError(request);
				return mapping.findForward("fail");	
				
			}else{
				System.out.println ("导出成功------！");
				addErrors("msg.syncsuccess");
				this.saveError(request);
			}
			
			
		}catch(Exception e){
			System.out.println ("处理产生错误：" + e.getMessage() );
			e.printStackTrace();
			this.addErrors(new ActionError(e.getMessage()));
			this.saveError(request);
			return mapping.findForward("fail");	
		}finally{
			wzw.util.DbUtils.closeQuietly(rs1);
			wzw.util.DbUtils.closeQuietly(rs2);
			wzw.util.DbUtils.closeQuietly(rs3); 
			wzw.util.DbUtils.closeQuietly(stmt);
			wzw.util.DbUtils.closeQuietly(stmt2);
			wzw.util.DbUtils.closeQuietly(stmt3); 
			wzw.util.DbUtils.closeQuietly(conn);
		}
		return null;
	}

	/**
	 * 取{...}之间的值。 eg:学号{ editHide:0, listHide:1,required:1,fieldType,list,order:3} 
	 * @param colBean
	 * @param colComm
	 * @return 
	 */
	private String setExtProperties(DatabaseColumnBean colBean, String colComm) {
		if (colComm==null) {
			return colComm;
		}
		int begin = colComm.indexOf("{");
		if (begin<0) {
			return colComm;
		}
		int end = colComm.lastIndexOf("}");
		if (end==begin) {
			return colComm;
		}
		String str = colComm.substring(begin+1, end);
		String[] proPaires = str.split(",");
		String[] property = null;
		for (String pair : proPaires) {
			property = pair.split(":");
			System.out.println("the str will be split is:"+pair);
			try {
				System.out.println("call setter,name="+property[0]+ " value="+property[1]);
				LangUtil.setProperty(colBean, property[0], property[1]);
			} catch (Exception e) {
				System.out.println("the str will be split and setProperty is:"+pair);
				try{
					colBean.getExt().put(property[0], property[1]);  //如果找不到相应的setter，放置到扩展属性中，模板采用 bean.ext.name取值
				} catch (Exception e2) {
					System.err.println("the str will be split and put to Ext properties is:"+pair);
				}
			}
		}
		colComm = colComm.substring(0,begin) + colComm.substring(end+1);
		return colComm;
	}

	/**
	 * 这里设置非自增类型主键
	 * @param tableBean
	 * @param columns
	 * @param t_name
	 */
	private void setColumnAsPrimaryKey(DatabaseTableBean tableBean, List<DatabaseColumnBean> columns,
			String t_name) {
		for (DatabaseColumnBean columnBean : columns) {
			if (columnBean.getName().equals(t_name)) {
				
				//如果前面没有添加该PK，则添加
				for (DatabaseColumnBean pkColBean : tableBean.getPrimaryKey()) {
					if( pkColBean.getName().equals(t_name)){
						return;
					}
				}
				columnBean.setIsPrimaryKey(1);
				columnBean.setIsAutoincrement(0);
				//如果前面设置不对，此处校正
				tableBean.getPrimaryKey().add( columnBean );   //主键添加
				//tableBean.getInsertColumns().remove(columnBean);
				tableBean.getUpdateColumns().remove(columnBean);  //更新列=所有列-主键列
				
				break;
			}
		}
		
	}

	private static boolean testResultSet(Connection conn) throws SQLException{ 
		//test rs  
		String sql="select csm,cszwm,type from fx_bb_bbcsxx where SFZCX='1' and  bbbh='0606'" ; 
		Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY ) ;
		ResultSet rs = stmt.executeQuery(sql);
		
			System.out.println("---------2005-8-4 ") ;
		if(rs.next()){
			rs.last() ;
			System.out.println("---------2005-8-4 " + rs.getRow() );
		
			rs.beforeFirst() ;
			System.out.println("---------2005-8-4");
		}
		 
		//rs=stmt.executeQuery(sql);
		int i=0;
		String csm = new String() ;
		boolean isFirstRow = true ;
		while(rs.next()){
			System.out.println ("value = " +  rs.getString("cszwm") );
		}
			System.out.println("---------2005-8-4 end ok");
		return true ;
	}	
	
	/**
	 * 
	 * <p>替换回车换行符号</p>
	 * @author Zeven on Jan 29, 2010
	 * @param str
	 * @return
	 */
	public static String toOneRow(String str){
		return str.replaceAll("\n","").replaceAll("\r","");
	}
	
	/**
	 * <p>java方法的说明...</p>
	 * @author Zeven on Jan 29, 2010
	 * tags
	 */
	public static void main(String[] args) {
		
	}
	
}

